package com.yjf.ljr.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.CustomerManageDataClass;
import com.yjf.ljr.dataclass.CustomerManageDataClass.CustomerManageInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

/**
 * 客户管理
 * 
 * @author dongxie
 * 
 */
public class CustomerManageActivity extends IjActivity implements OnClickListener {

	public static final int REQUEST_CODE_INCOME_SETTING = 2000; // 收益配置

	@ID("xlvCustomerManage")
	private XListView mXlvCustomerManage;
	@ID("tvDevelopedInvestPeoples")
	private TextView mTvDevelopedInvestPeoples;
	@ID("btnInvestOpenAccount")
	private Button mBtnInvestOpenAccount;
	private CommonAdapter mCommonAdapter;
	private List<CustomerManageInfo> mData = new ArrayList<CustomerManageInfo>();
	private final int mPageSize = 10;
	private int mCurPage = 1;
	private boolean mIsGettingData = false;
	private int mCurIndex = 0;
	static CustomerManageActivity instance;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customer_manage);
		initControls();
		loadingData(mPageSize, mCurPage, false, true);
		instance = this;
	}

	/** 初始化控件 **/
	private void initControls() {
		setLeftBtnClick();
		setTitleStr("客户管理");

		mBtnInvestOpenAccount.setOnClickListener(this);
		mCommonAdapter = new CommonAdapter(this, mData, R.layout.item_customer_manage, ViewHolder.class,
				mHandleCallBack);
		mXlvCustomerManage.setAdapter(mCommonAdapter);
		mXlvCustomerManage.setPullLoadEnable(true);
		mXlvCustomerManage.setPullRefreshEnable(true);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mXlvCustomerManage.setRefreshTime(sdf.format(new Date()));
		mXlvCustomerManage.mFooterView.hide(); // 隐藏更多
		mXlvCustomerManage.setXListViewListener(new MyXListViewListener());
		mXlvCustomerManage.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mCurIndex = position - 1;
				CustomerManageInfo info = mData.get(mCurIndex); // XListView 有头
				if (!TextUtils.isEmpty(info.customerId)) {
					Intent intent = new Intent(CustomerManageActivity.this, IncomeSettingActivity.class);
					intent.putExtra("customerId", info.customerId);
					startActivityForResult(intent, REQUEST_CODE_INCOME_SETTING);
				}

			}
		});
	}

	private class MyXListViewListener implements IXListViewListener {
		@Override
		public void onRefresh() {
			mCurPage = 1;
			loadingData(mPageSize, mCurPage, false, false);
		}

		@Override
		public void onLoadMore() {
			loadingData(mPageSize, ++mCurPage, true, false);
		}
	}

	private void loadingData(int pageSize, int curPage, boolean isAdd, boolean showProgress) {
		if (mIsGettingData) {
			return;
		}
		if (showProgress) {
			showProgressDialog();
		}
		new CustomerManageTask(pageSize, curPage, isAdd).execute();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnInvestOpenAccount:
			startActivity(new Intent(CustomerManageActivity.this, InvestorsOpenAccountActivity.class));
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:
				mCurPage = 1;
				showProgressDialog();
				new CustomerManageTask(mPageSize, mCurPage, false).execute();
				break;
			case REQUEST_CODE_INCOME_SETTING:
				if (intent != null) {
					String limit = intent.getStringExtra("limit");
					if (!TextUtils.isEmpty(limit)) {
						CustomerManageInfo info = mData.get(mCurIndex);
						info.profit = limit;
						mData.set(mCurIndex, info);
						mCommonAdapter.notifyDataSetChanged();
					}
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	class CustomerManageTask extends AsyncTask<Void, Void, String> {

		private int pageSize;
		private int curPage;
		private boolean isAdd = false;
		private CustomerManageDataClass dc = new CustomerManageDataClass();

		public CustomerManageTask(int pageSize, int curPage, boolean isAdd) {
			super();
			this.pageSize = pageSize;
			this.curPage = curPage;
			this.isAdd = isAdd;
		}

		@Override
		protected void onPreExecute() {
			mIsGettingData = true;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject requestobj = new RequestObject();
			requestobj.method = "appCustomerManager";
			requestobj.map.put("pageSize", pageSize);
			requestobj.map.put("pageNumber", curPage);
			return requestDataAndGetErrorMsg(requestobj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
				mCommonAdapter.notifyDataSetChanged();
				mXlvCustomerManage.mFooterView.hide();
			} else {
				if ("0".equals(dc.investorsCount + "")) {
					dismissProgressDialog();
					showToast(dc.msg);
					return;
				}
				if (!isAdd) {
					mData.clear();
				}

				if (dc.investorManage != null && dc.investorManage.size() > 0) {
					mData.addAll(dc.investorManage);
					mCommonAdapter.notifyDataSetChanged();

					if (mData.size() < dc.investorsCount) {
						mXlvCustomerManage.mFooterView.show();
					} else {
						if ("0".equals(dc.investorsCount)) {
							showToast(dc.msg);
						} else {
							mXlvCustomerManage.mFooterView.hide();
						}
					}
					String peoples = "累计已发展投资人：<font color='#ff6600'>" + dc.investorsCount + "</font>人";
					AppUtil.setViewHtml(mTvDevelopedInvestPeoples, peoples);
				}
			}
			mXlvCustomerManage.stopRefresh();
			mXlvCustomerManage.stopLoadMore();
			dismissProgressDialog();
			mIsGettingData = false;
		}
	}

	public static class ViewHolder {
		private TextView tvRealName;
		private TextView tvStatus;
	}

	private HandleCallBack mHandleCallBack = new HandleCallBack() {

		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			CustomerManageInfo info = (CustomerManageInfo) item;
			ViewHolder h = (ViewHolder) holder;
			if (TextUtils.isEmpty(info.realName)) {
				AppUtil.setViewText(h.tvRealName, info.userName);
			} else {
				AppUtil.setViewText(h.tvRealName, info.realName);
			}
			AppUtil.setViewText(h.tvStatus, info.status + "/" + info.profit);
		}
	};
}